/**
* @Author: 李晨光
* @Date: 2019/12/12
* @Version: 1.0
* @Last Modified by: 李晨光
* @Last Modified time: 2019/12/12
**/
<comment>
  # 文件上传组件
</comment>
<template>
  <div id="FileUpload">
    <mu-flex justify-content="center" slot="upload-btn">
      <!-- <mu-button @click="sheetVisible = !sheetVisible">打开</mu-button> -->
      <div class="imgTrigger" @click="sheetVisible = true">
        <i class="iconfont iconpaizhao"></i>
        <span>添加照片</span>
      </div>
    </mu-flex>
    <mt-actionsheet :actions="actions" v-model="sheetVisible"></mt-actionsheet>
    <div v-show="false">
      <!--camera 拍照-->
      <input
        type="file"
        v-if="back"
        ref="camera"
        :accept="accept"
        name="file"
        @change="fileChange($event)"
        capture="camera"
      />
      <!--选择文件-->
      <input type="file" v-if="back" ref="file" :accept="accept" @change="fileChange($event)" />
      <!--camcorder 录像-->
      <input
        type="file"
        v-if="back"
        ref="camcorder"
        accept="video/*"
        @change="fileChange($event)"
        capture="camcorder"
      />
    </div>
  </div>
</template>

<script>
// import ImageCompressor from 'image-compressor.js';
import axios from "axios";

export default {
  name: "FileUpload",
  components: {},
  props: {
    // camera  camcorder  file
    type: {
      type: String,
      default: "camera"
    },
    accept: {
      type: String,
      default: "image/*"
    },
    multiple: {
      type: Boolean,
      default: false
    },
    // 默认 5M 5242880
    size: {
      type: Number,
      default: 5242880
    },
    headers: {
      type: Object,
      default: () => {
        return {};
      }
    },
    data: {
      type: Object,
      default: () => {
        return {};
      }
    }
  },
  data() {
    return {
      sheetVisible: false,
      actions: [
        {
          name: "拍照",
          method: this.getCamera
        },
        {
          name: "录像",
          method: this.getCamcorder
        },
        {
          name: "从相册中选择",
          method: this.getLibrary
        },
        {
          name: "从本地文件中选择",
          method: this.getFileLibrary
        }
      ],
      precent: 0,
      back: true
    };
  },
  computed: {},
  created() {
    this.$nextTick(() => {
      // this.dealCapture()
    });
  },
  mounted() {},
  watch: {
    type: {
      handler(newVal, oldVal) {
        switch (newVal) {
          case "camera":
            this.actions = [
              {
                name: "拍照",
                method: this.getCamera
              },
              {
                name: "从本地选择",
                method: this.getLibrary
              }
            ];
            break;
          case "camcorder":
            this.actions = [
              {
                name: "录像",
                method: this.getCamcorder
              },
              {
                name: "从本地选择",
                method: this.getLibrary
              }
            ];
            break;
          case "file":
            this.actions = [
              {
                name: "从本地选择",
                method: this.getFileLibrary
              }
            ];
            break;
          case "lib":
            this.actions = [
              {
                name: "从本地选择",
                method: this.getLibrary
              }
            ];
            break;
        }
      },
      immediate: true
    }
  },
  methods: {
    dealCapture() {
      if (this.getIos()) {
        this.$refs.camera.removeAttribute("capture");
        this.$refs.file.removeAttribute("capture");
        this.$refs.camcorder.removeAttribute("capture");
      }
    },
    getIos() {
      if (!!navigator.userAgent.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/)) {
        return true;
      } else {
        return false;
      }
    },
    getCamera() {
      this.$refs.camera.dispatchEvent(new MouseEvent("click"));
      console.log("打开照相机");
    },
    getLibrary() {
      console.log("打开相册");
      this.$refs.file.dispatchEvent(new MouseEvent("click"));
    },
    getCamcorder() {
      this.$refs.camcorder.dispatchEvent(new MouseEvent("click"));
    },
    getFileLibrary() {
      this.$refs.file.dispatchEvent(new MouseEvent("click"));
    },
    fileChange(e) {
      if(this.size < e.target.files[0].size) {
        // this.$A.MS(`文件大小不能超过${this.handsize(this.size)}`)
        this.$A.MS(`文件大小不能超过5M`)
        return
      }
      //拍照功能---上传头像
      let file = e.target.files[0]; //获取文件对象
      let fd = new FormData(); //构造formdata对象
      fd.append("file", file); //向formdata里面存放键值对
      let userinfo = this.$A.GS('userInfo')
      let nda = `${new Date().toLocaleDateString()} ${new Date().toTimeString().substring(0,8)}${userinfo['userName']}${userinfo['userNumber']}`
      fd.append("waterMark", nda);
      this.uploadFile(
        fd,
        res => {
          console.log(res);
        },
        progress => {
          let loaded = progress.loaded,
            total = progress.total;
          this.$nextTick(() => {
            this.precent = (loaded / total) * 100;
          });
          console.log(progress);
        },
        err => {
          console.log(err);
        }
      );
    },
    uploadFile(payload, callbackSuccess, callbackProgress, callbackError) {
      console.log(payload)
      this.$openLoading("上传中");
      axios({
        url: process.env.API_ROOT + "/safety/system/upload",
        method: "post",
        onUploadProgress: progressEvent => {
          //原生获取上传进度的事件
          if (progressEvent.lengthComputable) {
            //属性lengthComputable主要表明总共需要完成的工作量和已经完成的工作是否可以被测量
            //如果lengthComputable为false，就获取不到progressEvent.total和progressEvent.loaded
            callbackProgress(progressEvent);
          }
        },
        data: payload
      })
        .then(res => {
          callbackSuccess(res);
          this.$emit("successed", res);
          this.$closeLoading();
          this.sheetVisible = false;
          this.back = false;
          setTimeout(() => {
            this.back = true;
          });
        })
        .then(error => {
          console.log(error);
          this.$closeLoading();
          this.$emit("failed", error);
          callbackError(error);
          this.sheetVisible = false;
          this.back = false;
          setTimeout(() => {
            this.back = true;
          });
        });
    },
    //计算大小
    handsize(number) {
      if (number > 0) {
        if (number / 1024 < 1024) {
          return (number / 1024).toFixed(2) + "KB";
        }
        if (number / 1024 >= 1024 && number / 1024 <= 1024) {

          return parseFloat(number / 1024 / 1024).toFixed(2)+ "M";

        } else {
          return parseFloat(number / 1024 / (1024 * 1024)).toFixed(2) + "G";
        }
      }
    },
  },
  destroyed() {}
};
</script>

<style lang="scss" scoped>
.imgTrigger {
  height: 0.7rem;
  width: 0.7rem;
  background-color: #f8f8f8;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}
</style>
